import { MomentInput, Moment } from 'moment';
import { createContext, FunctionComponent, useCallback } from 'react';
import QuerySiteSettings from 'calypso/components/data/query-site-settings'; // Required to get site time offset
import { applySiteOffset } from 'calypso/lib/site/timezone';
import { useSelector } from 'calypso/state';
import getSiteGmtOffset from 'calypso/state/selectors/get-site-gmt-offset';
import getSiteTimezoneValue from 'calypso/state/selectors/get-site-timezone-value';
import { getSiteId } from 'calypso/state/sites/selectors';

export type contextTypeLoaded = ( input: MomentInput ) => Moment;
export type contextType = contextTypeLoaded | null;

const SiteOffsetContext = createContext< contextType >( null );

interface Props {
	site: string;
	children?: React.ReactNode;
}

const SiteOffsetProvider: FunctionComponent< Props > = ( { children, site } ) => {
	// hackery here to get around
	const siteId = useSelector( ( state ) => getSiteId( state, site ) ) as number | null;

	const gmtOffset = useSelector( ( state ) =>
		siteId ? getSiteGmtOffset( state, siteId ) : null
	);
	const timezone = useSelector( ( state ) =>
		siteId ? getSiteTimezoneValue( state, siteId ) : null
	);

	const value = useCallback(
		( input: MomentInput ) => applySiteOffset( input, { gmtOffset, timezone } ),
		[ gmtOffset, timezone ]
	);

	return (
		<>
			{ siteId && <QuerySiteSettings siteId={ siteId } /> }
			<SiteOffsetContext.Provider value={ gmtOffset !== null || timezone !== null ? value : null }>
				{ children }
			</SiteOffsetContext.Provider>
		</>
	);
};

export { SiteOffsetContext, SiteOffsetProvider };
